package com.jinyi.wwdeng.ui.steps.fragment

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.FragmentActivity
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.jinyi.base.utils.img.ImageUtil
import com.jinyi.base.utils.log.HHLog
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.FragmentStepFaceBinding
import com.jinyi.wwdeng.network.ApiService
import com.jinyi.wwdeng.network.HttpBaseParams.addCommonParams
import com.jinyi.wwdeng.pro.ProAct
import com.jinyi.wwdeng.pro.ProFragment
import com.jinyi.wwdeng.ui.permission.PermissionListener
import com.jinyi.wwdeng.ui.permission.PermissionUtils
import com.jinyi.wwdeng.ui.steps.act.OcrCameraFaceAct
import com.jinyi.wwdeng.ui.steps.act.StepListAct
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import org.json.JSONObject
import java.io.File

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/23 10:31
 * @Annotation：人脸识别
 */
class StepFaceFragment: ProFragment() {

    lateinit var binding: FragmentStepFaceBinding
    //本地预览地址
    var faceImgPath = ""
    //拍摄的头像地址
    var faceImgUrl = ""

    override fun getRootView(inflater: LayoutInflater): View {
        binding = FragmentStepFaceBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        showFaceBeforeView()
    }

    override fun initListener() {
        //开始 、 提交
        binding.btnStartOrSubmit.setOnClickListener {
            //开始人脸拍照
            if (faceImgUrl.isEmpty()){
                if (XXPermissions.isGranted(requireContext(),Permission.CAMERA)){
                    TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_STEP_FACE_START_TAKE,"")
                    faceCameraResultLauncher.launch(Intent(context,OcrCameraFaceAct::class.java))
                } else {
                    XXPermissions.with(requireContext())
                        // 申请多个权限
                        .permission(Permission.CAMERA)
                        .request(object: OnPermissionCallback {
                            override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,Permission.CAMERA)
                                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_STEP_FACE_START_TAKE,"")
                                faceCameraResultLauncher.launch(Intent(context,OcrCameraFaceAct::class.java))
                            }
                            override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_SYSTEM_DENY,Permission.CAMERA)
                                XXPermissions.startPermissionActivity(context!!,permissions)
                            }
                        })
                }
                return@setOnClickListener
            }
            //提交
            val params = JSONObject().addCommonParams().apply {
                put("path", ApiService.API_PATH.API_PATH_OCR_INFO)
                put("cardType","FACE")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("faceImgUrl",faceImgUrl)//人脸图片
            }
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_STEP_FACE_CONFIRM_SUBMIT,"")
            val act = context as StepListAct
            act.onSubmitRequest(params)
        }

        //删除
        binding.imgRemove.setOnClickListener {
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_STEP_FACE_REMOVE_PHOTO,faceImgUrl)
            if (faceImgPath.isNotEmpty()){
                //删除图片
                val imgFile = File(faceImgPath)
                if (imgFile.isFile){
                    imgFile.delete()
                }
                faceImgPath = ""
            }
            faceImgUrl = ""
            showFaceBeforeView()
        }
    }

    override fun initData() {
    }

    /**
     * 人脸拍照
     */
    private val faceCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            FragmentActivity.RESULT_OK -> {
                faceImgUrl = result.data!!.getStringExtra("faceImgUrl").toString()
                faceImgPath = result.data!!.getStringExtra("faceImgPath").toString()
                showFaceAfterView()
                HHLog.e(">>>>>>>>>人脸拍照后返回照片地址："+result.data!!.getStringExtra("faceImgUrl"))
            }
        }
    }

    /**
     * 显示未拍照View
     */
    private fun showFaceBeforeView(){
        binding.imgHeader.setImageResource(R.mipmap.pic_face_detection_icon)
        binding.imgRemove.visibility = View.GONE
        binding.btnStartOrSubmit.text = getString(R.string.start_taking_a_selfie)
    }

    /**
     * 显示拍照之后的View
     */
    private fun showFaceAfterView(){
        ImageUtil.getInstance().loadImage(context,binding.imgHeader,faceImgPath)
        binding.imgRemove.visibility = View.VISIBLE
        binding.btnStartOrSubmit.text = getString(R.string.confirm_and_submit)
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_STEP_FACE_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_STEP_FACE_END,"")
    }
}